﻿using pHM.DVBLib.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace LungSoundWizard.Classes
{
    public static class ReferenceSnippetReader
    {
        public static ReferenceSnippets Snippets { get; set; }

        static ReferenceSnippetReader()
        {
            try
            {
                Snippets = ReadSnippets("ref_snippets.xml");
            }
            catch (Exception ex)
            {
                Logger.AddLogItem("Error reading ref. snippets file", "ReferenceSnippetReader", LogLevels.Error, ex);
                Snippets = new ReferenceSnippets();
            }
        }

        public static void Save()
        {
            SaveSnippets("ref_snippets.xml", Snippets);
        }

        static void SaveSnippets(string filename, ReferenceSnippets snippets)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(ReferenceSnippets));

            using (TextWriter writer = new StreamWriter(filename))
            {
                serializer.Serialize(writer, snippets);
            }
        }

        static ReferenceSnippets ReadSnippets(string filename)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(ReferenceSnippets));
            serializer.UnknownNode += serializer_UnknownNode;
            serializer.UnknownAttribute += serializer_UnknownAttribute;

            using (FileStream fs = new FileStream(filename, FileMode.Open))
            {
                ReferenceSnippets snippets = (ReferenceSnippets)serializer.Deserialize(fs);

                Logger.AddLogItem(string.Format("Read {0} snippets", snippets.Snippets.Length), "ReferenceSnippetReader", LogLevels.Information);

                return snippets;
            }
        }

        static void serializer_UnknownAttribute(object sender, XmlAttributeEventArgs e)
        {
            Logger.AddLogItem("Unknown XML attribute in ref snippet file", "ReferenceSnippetReader", LogLevels.Warning);
        }

        static void serializer_UnknownNode(object sender, XmlNodeEventArgs e)
        {
            Logger.AddLogItem("Unknown XML node in ref snippet file", "ReferenceSnippetReader", LogLevels.Warning);
        }
    }
}
